Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

238
Visualizações
Trying to fetch from API but getting [object Promise] instead

I'm trying to make a website that fetches a random 10 lines from a poem and then outputs them in the HTML file but instead of getting the .json data I'm getting [object Promise]. Can someone help me out?

Here's my code:

JS:

let url = 'https://poetrydb.org/random,linecount/1;10/title,author,lines.json'
const button = document.getElementById('button')
const body = document.getElementById('poem')

async function requestPoem(url) {
    await fetch(url)
    .then((response)=>{
        let data = response.json()
        return data
    })
}

button.onclick = ()=>{
    body.innerHTML = requestPoem(url)
}

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script defer src="scripts/main.js"></script>
    <title>poem request</title>
</head>
<body>
    <p id="poem"></p>
    <button id="button">request poem</button>
</body>
</html>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

requestPoem is an async function, so it can only ever return a promise. You can't avoid the promise, but you can use it, either by calling .then on it, or by putting your code in an async function and awaiting the result. Also, your current requestPoem function has no return statement, so it will need one to define what the promise resolves to.

async function requestPoem(url) {
  const response = await fetch(url);
  return response.json();
}

button.onclick = async () => {
  body.innerHTML = await requestPoem(url);
}
about 4 years ago · Juan Pablo Isaza Relatório

0

Turns out the mistake in the code was that the API was returning an array of objects instead of a single object. Because of this I first had to return data[0] and get the object's properties from there.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda